package com.lms.common.web.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.lms.common.pure.entity.IBaseEntity;
import com.lms.common.pure.query.QueryParams;
import com.lms.common.web.service.IBaseService;
import com.lms.common.web.utils.CheckEntityResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

@RestController
public abstract class BaseController<S extends IBaseService<T>, T extends IBaseEntity> {
    @Autowired
    protected S baseService;

    @Autowired
    protected HttpServletRequest request;

    @Autowired
    protected HttpServletResponse response;

    @Operation(summary = "通用表格查询方法")
    @PostMapping("/query")
    public IPage<?> query(@Parameter(description = "查询参数") @RequestBody QueryParams<Map<String, Object>> queryParams) {
        return this.baseService.query(queryParams);
    }

    @Operation(summary = "根据主键id获取相应实体或View信息")
    @GetMapping("/get/{id}")
    public Object get(@PathVariable("id") @Parameter(description = "主键id") Serializable id) {
        return this.baseService.get(id);
    }

    @Operation(summary = "根据条件获取相应实体或View信息")
    @PostMapping("/getByFilter")
    public Object getByFilter(@Parameter(description = "查询参数") @RequestBody Map<String, Object> queryParams) {
        return this.baseService.getByFilter(queryParams);
    }

    @Operation(summary = "通用保存方法")
    @PostMapping("/save")
    public T save(@Parameter(description = "保存的实体类信息") @RequestBody Map<String, Object> entity) {
        return this.baseService.saveEntity(entity);
    }

    @Operation(summary = "保存前的校验方法")
    @PostMapping("/beforeSaveCheck")
    public CheckEntityResult beforeSaveCheck(@Parameter(description = "需要校验的保存对象") @RequestBody T entity) {
        if (entity.getKey() != null) {
            return this.baseService.beforeUpdate(entity, entity.getKey());
        }
        return this.baseService.beforeInsert(entity);
    }

    @Operation(summary = "根据主键id删除单条信息")
    @DeleteMapping("/delete/{id}")
    public void delete(@Parameter(description = "主键id") @PathVariable("id") Serializable id) {
        this.baseService.delete(id);
    }

    @Operation(summary = "根据主键id集合删除多条信息")
    @PostMapping("/deleteBatch")
    public void deleteBatch(@Parameter(description = "主键id集合") @RequestBody List<Serializable> ids) {
        this.baseService.deleteBatch(ids);
    }

    @Operation(summary = "通用导出excel")
    @PostMapping("/exportExcel")
    public void exportExcel(@Parameter(description = "查询参数") @RequestBody QueryParams<Map<String, Object>> queryParams) {
        this.baseService.exportExcel(queryParams, response);
    }

}
